from django.template import RequestContext
from django.http import HttpResponse, HttpResponseRedirect, Http404
from django.shortcuts import render_to_response, get_object_or_404
from django.contrib.auth.models import User
from django.utils import simplejson

from online_shop.orders.forms import CommentAndRateForm

from online_shop.cart import cart
from online_shop.orders.models import address,orders,order_details, order_status, product_rates
from online_shop.users.models import comments
from online_shop.products.models import product_rates_value, inventory_records



# Create your views here.

# Make comment and rate page
#  After confirm receiving goods, system will aotumatically jump to this page asking user to make comment and rate for the goods.
# url: order/<order_id>/makeCommentAndRate/
def make_comment_and_rate_page(request, order_id):
    
    # get order object
    order = get_object_or_404(orders,id=order_id)
    
    # validate the status of order, only after goods arrived, this page can open
    if order.status.type == 'ARRIVED' or order.status.type == 'FINISH':
        # validate the permisson of the ruquest user, only the order own have the permission to access
        user = User.objects.get(username=request.user.username)
        if order.iduser != user:
            raise Http404
        if request.method == "POST":
            submit_form = CommentAndRateForm(request.POST)
            if submit_form.is_valid():
                order_detail = get_object_or_404(order_details,id=submit_form.cleaned_data['o_detail'])
                rate = product_rates()
                rate.order_detail = order_detail
                rate.value = int(submit_form.cleaned_data['rate'])                
                rate.save()
                
                # calaculate average rate
                try:
                    rates_value = product_rates_value.object.get(product=order_detail.idproduct)
                except:
                    rates_value = product_rates_value()
                    rates_value.product = order_detail.idproduct
                rate_results = product_rates.objects.filter(order_detail__idproduct=order_detail.idproduct)
                sum = 0
                for r in rate_results:
                    sum = sum + r.value
                rates_value.count = rate_results.count()
                rates_value.value = sum/rates_value.count
                rates_value.save()
                
                if submit_form.cleaned_data['comment']!='' :
                    comment = comments()
                    comment.order_detail = order_detail
                    comment.product = order_detail.idproduct
                    comment.user = order.iduser
                    comment.content = submit_form.cleaned_data['comment']
                    comment.save()
                
                #check if all the products has been rate and comment
                o_details = order_details.objects.filter(idorder=order_id)
                num = 0
                for o_detail in o_details:
                    try:
                        if o_detail.product_rates and o_detail.comments:
                            num = num + 1
                    except:
                        break;
                if num == o_details.count():
                    order.status = order_status.objects.get(type="FINISHED")
                    order.save()
        #o_detail_results = order_details.objects.filter(idorder=order)
        variables = RequestContext(request,{
            'order': order,
            'form': CommentAndRateForm(),
            'amount': cart.cart_distinct_item_count(request),
        })
    
        return render_to_response(
            'orders/comment_and_rate.html',
            variables,
        )        
    else:
        raise Http404    
    

def payment_success(request):
    if request.method=='GET':
        order_id = request.GET.get('pid',0)
    my_order = get_object_or_404(orders,id=order_id)
    status = get_object_or_404(order_status,type='PROCESSED')
    my_order.status = status
    my_order.save()
    #change the inventory information
    o_details = order_details.objects.filter(idorder=my_order)
    for o_detail in o_details:
        inventory = inventory_records.objects.get(product=o_detail.idproduct)
        inventory.available = inventory.available - o_detail.count
        inventory.save()
       
    return HttpResponseRedirect(
        '/'
    )

def show_orders(request):
    total_orders_num = 0
    processed_num = 0
    shipped_num = 0
    arrived_num = 0
    finished_num = 0
    cancelled_num = 0
    user = get_object_or_404(User, username=request.user.username)
    my_orders = user.orders_user.all()
    total_orders_num = len(my_orders)
    for my_order in my_orders:
        if my_order.status.type=='PROCESSED':
            processed_num+=1
        elif my_order.status.type=='SHIPPED':
            shipped_num+=1
        elif my_order.status.type=='ARRIVED':
            arrived_num+=1
        elif my_order.status.type=='FINISHED':
            finished_num+=1
        elif my_order.status.type=='CANCELED':
            cancelled_num+=1
    variables = RequestContext(request, {
        'orders': my_orders,
        'total_orders_num': total_orders_num,
        'processed_num': processed_num,
        'shipped_num': shipped_num,
        'arrived_num': arrived_num,
        'finished_num': finished_num,
        'cancelled_num': cancelled_num,
    })
    return render_to_response(
        'User_panel/order_management/show_orders.html',
        variables,
    )

def show_order_details(request, order_id):
    if not request.user.is_authenticated():
        return HttpResponseRedirect('/login/')
    my_order = get_object_or_404(orders, id=order_id)
    if request.user.username == my_order.iduser.username:
        if my_order.status.type=='SHIPPED':
            status_shipped = True
        else:
            status_shipped = False
        my_order_details = order_details.objects.filter(idorder=my_order)
        my_address = my_order.idaddress
        total_price = 0
        for my_order in my_order_details:
            total_price += my_order.count * my_order.unit_price
    else:
        raise Http404
    variables = RequestContext(request, {
        'my_order_id': order_id,
        'order_details': my_order_details,
        'status_shipped': status_shipped,
        'my_address': my_address,
        'total_price': total_price
    })
    return render_to_response(
        'User_panel/order_management/show_order_details.html',
        variables,
    )
def shipped_to_arrived(request):
    if request.method=='POST':
        postdata = request.POST.copy()
        my_order_id = postdata.get('order_id', 0)
        my_order = get_object_or_404(orders, id=my_order_id)
        status = get_object_or_404(order_status,type='ARRIVED')
        my_order.status = status
        my_order.save()
    return HttpResponseRedirect(
        '/order/'+my_order_id+'/makeCommentAndRate/'
    )

def order_filter(request, type=''):
    total_orders_num = 0
    processed_num = 0
    shipped_num = 0
    arrived_num = 0
    finished_num = 0
    cancelled_num = 0
    user = get_object_or_404(User, username=request.user.username)
    my_orders = user.orders_user.all()
    total_orders_num = len(my_orders)
    for my_order in my_orders:
        if my_order.status.type=='PROCESSED':
            processed_num+=1
        elif my_order.status.type=='SHIPPED':
            shipped_num+=1
        elif my_order.status.type=='ARRIVED':
            arrived_num+=1
        elif my_order.status.type=='FINISHED':
            finished_num+=1
        elif my_order.status.type=='CANCELED':
            cancelled_num+=1
    if type=='PROCESSED':
        status = get_object_or_404(order_status, type='PROCESSED')
    elif type=='SHIPPED':
        status = get_object_or_404(order_status, type='SHIPPED')
    elif type=='ARRIVED':
        status = get_object_or_404(order_status, type='ARRIVED')
    elif type=='FINISHED':
        status = get_object_or_404(order_status, type='FINISHED')
    elif type=='CANCELED':
        status = get_object_or_404(order_status, type='CANCELLD')
    my_orders = orders.objects.filter(iduser=user, status=status)
    variables = RequestContext(request,{
        'orders': my_orders,
        'total_orders_num': total_orders_num,
        'processed_num': processed_num,
        'shipped_num': shipped_num,
        'arrived_num': arrived_num,
        'finished_num': finished_num,
        'cancelled_num': cancelled_num,
    })
    return render_to_response(
        'User_panel/order_management/show_orders.html',
        variables,
    )

# Add new comment and rate to database
# url: order/<order_id>/makeCommentAndRate/add/<o_detail_id>
def ajax_add_new_comment_and_rate(request,order_id, o_detail_id):
    # validate the status of order, if the commest and rates has been made, return False
    
    # validate the permisson of the ruquest user, only the order own have the permission to access
    # **TODO: This part should be modified later
    
    
    return ''
    
    
    